# -*- coding: utf-8 -*-
import base64
import hashlib
import json
from collections import OrderedDict

import requests
from Crypto.Cipher import AES
from Crypto.Cipher import AES as _AES
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'EQ41215904': {  # zs 支付宝2.8%（100-5000）
        'scan_gateway': 'http://api.wpay1.com/api/guest/pay/payApplyGetQrCode',
        'wap_gateway': 'http://api.wpay1.com/api/guest/pay/payApplyGetQrCodeH5',
        'api_key': "6611D38E6618BE8EF1783CA3753651FB",
        'query_gateway': 'http://api.wpay1.com/api/guest/pay/commercialInfo',
    },
}


def _get_scan_gateway(mch_id):
    return APP_CONF[mch_id]['scan_gateway']


def _get_wap_gateway(mch_id):
    return APP_CONF[mch_id]['wap_gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['api_key']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def _get_pay_type(service):
    if service == 'alipay':
        return '2'
    return '2'


# AES加密
def Encrypt(key, toEncrypt):
    toEncrypt = toEncrypt.encode("utf8")  # 转换为UTF8编码
    key = key.encode("utf8")
    bs = AES.block_size
    pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)  # PKS7
    cipher = _AES.new(key, AES.MODE_ECB)  # ECB模式
    resData = cipher.encrypt(pad(toEncrypt))
    return base64.b64encode(resData)


# AES解密
def Decrypt(key, encrData):
    encrData = base64.b64decode(encrData.encode("ascii"), ' /')
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]
    cipher = AES.new(key, AES.MODE_ECB)
    decrData = unpad(cipher.decrypt(encrData))
    return decrData.decode('utf-8')


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    parameter_dict = OrderedDict((
        ('payAmount', '%.2f' % pay_amount),
        ('commercialOrderNo', str(pay.id)),
        ('callBackUrl', '{}/pay/api/{}/huidingpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('notifyUrl', '{}/pay/api/{}/huidingpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('payType', _get_pay_type(service)),
    ))
    _LOGGER.info("huidingpay create encrypt data is: %s", json.dumps(parameter_dict) + _get_api_key(app_id))
    api_key = _get_api_key(app_id)
    parameter = Encrypt(api_key, json.dumps(parameter_dict))
    sign = generate_sign(json.dumps(parameter_dict))
    parameter_charge = OrderedDict((
        ('platformno', app_id),
        ('parameter', parameter),
        ('sign', sign),
    ))
    _LOGGER.info("huidingpay create: %s", json.dumps(parameter_charge))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_scan_gateway(app_id), data=parameter_charge, headers=headers, timeout=5, verify=False)
    _LOGGER.info("huidingpay create rsp : %s", response.text)
    data = json.loads(response.text)
    return {'charge_info': data['payUrl']}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("huidingpay notify data: %s", data)
    data_decrypt = json.loads(Decrypt(api_key, data['parameter']))
    _LOGGER.info("huidingpay notify data_decrypt: %s", data_decrypt)
    pay_id = data_decrypt['commercialOrderNo']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huidingpay event does not contain pay ID')
    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data_decrypt['result']
    trade_no = data_decrypt['orderNo']
    total_fee = float(data_decrypt['orderAmount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success' and total_fee > 0.0:
        _LOGGER.info('huidingpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = str(pay_order.id)
    parameter_dict = OrderedDict((
        ('commercialOrderNo', pay_id),
        ('type', '1'),
    ))
    _LOGGER.info("huidingpay create encrypt data is: %s", json.dumps(parameter_dict) + _get_api_key(app_id))
    api_key = _get_api_key(app_id)
    parameter = Encrypt(api_key, json.dumps(parameter_dict))
    sign = generate_sign(json.dumps(parameter_dict))
    parameter_charge = OrderedDict((
        ('platformno', app_id),
        ('parameter', parameter),
        ('sign', sign),
    ))
    _LOGGER.info("huidingpay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_charge, headers=headers, timeout=5,
                             verify=False)
    _LOGGER.info("huidingpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = unicode(data['status'])
        trade_no = str(data['orderNo'])
        total_fee = float(data['orderAmount'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == u'支付成功':
            _LOGGER.info('huidingpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('huidingpay data error, status_code: %s', response.status_code)
